package com.zxy.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.json.JSONArray;
import org.json.JSONObject;

import sun.misc.BASE64Decoder;

import com.zxy.common.Com_Fun;
import com.zxy.common.Com_Para;

@SuppressWarnings("serial")
public class UploadFileServlet extends HttpServlet
{
	private String	uploadPath	= "";	// 上传文件的目录
	private String	tempPath	= "";	// 临时文件目录
	File			tempPathFile;

	public UploadFileServlet()
	{
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		if(com.zxy.common.Com_Para.UpLoad_File.equals(""))
		{
			uploadPath = Com_Fun.GetAbsPath() + "upload";
			tempPath = Com_Fun.GetAbsPath() + "temp";
		}else
		{
			uploadPath = com.zxy.common.Com_Para.UpLoad_File;
			tempPath = com.zxy.common.Com_Para.UpLoad_File + "/temp";
		}

		response.setContentType("text/html");
		request.setCharacterEncoding("utf-8");
		OutputStream out = response.getOutputStream();
		DiskFileUpload fu = new DiskFileUpload();
		// 设置允许用户上传文件大小,单位:字节
		// fu.setSizeMax(10000000);
		// 设置最多只允许在内存中存储的数据,单位:字节
		// fu.setSizeThreshold(4096);
		// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
		// (临时存放目录,文件上传完毕后有办法清除它吗？)
		fu.setRepositoryPath(tempPath + "//");
		// 开始读取上传信息
		List fileItems = null;
		try
		{
			fileItems = fu.parseRequest(request);
		}
		catch(Exception e1)
		{
			String strError = "{\"A01_UpLoadFile\":[{\""+Com_Fun.getLowUpp("s_result")+"\":\"0\",\""+Com_Fun.getLowUpp("error_desc")+"\":\"附件错误,info:"
					+ e1.getMessage() + "\"}]}";
			out.write(strError.getBytes(Com_Para.U_CODE));
			out.flush();
			out.close();
		}

		JSONObject jso = new JSONObject(new LinkedHashMap());
		JSONArray jsary = new JSONArray();
		try
		{
			String FileDate = "";
			if(java.util.Objects.equals(request.getParameter("FileDate"),null)
					|| request.getParameter("FileDate").toString().equals(""))
				FileDate = Com_Fun.DateTimeStr("yyyy-MM-dd");
			else
				FileDate = request.getParameter("FileDate").toString();
			// 依次处理每个上传的文件
			Iterator iter = fileItems.iterator();
			while(iter.hasNext())
			{
				FileItem item = (FileItem) iter.next();
				// 忽略其他不是文件域的所有表单信息
				if(!item.isFormField())
				{
					JSONObject temjso = new JSONObject(new LinkedHashMap());
					String oldName = item.getName();// 获取上传的文件名
					String[] attAry = oldName.split("\\.");
					String strAtt = "";
					if(attAry.length > 1)
						strAtt = attAry[attAry.length - 1];
					boolean bFlag = false;
					String[] UploadFileAtt = Com_Fun.GetHashTable(Com_Para.ht_T_PARAM_VALUE,"UploadFileAtt").split(",");
					for(String strAllowAtt: UploadFileAtt)
					{
						if(("." + strAtt.toUpperCase()).equals(strAllowAtt.toUpperCase()))
						{
							bFlag = true;
							break;
						}
					}
					if(!bFlag)
					{
						if(!item.getName().equals(""))
						{
							item.delete();
							temjso.put(Com_Fun.getLowUpp("oldFileName"),"上传附件失败，不符合上传文件格式");
							temjso.put(Com_Fun.getLowUpp("newFileName"),"");
							jsary.put(temjso);
						}
					}else
					{
						String newName = com.zxy.common.Com_Fun.Get_New_GUID().replace("-","")
								+ "." + strAtt;

						temjso.put(Com_Fun.getLowUpp("oldFileName"),oldName);
						temjso.put(Com_Fun.getLowUpp("newFileName"),newName);

						long size = item.getSize();// 获取上传的文件大小(字节为单位)
						if((java.util.Objects.equals(oldName,null)
								|| oldName.equals("")) && size == 0)
							continue;// 跳到while检查条件
						// 以下为文件名处理，将上传的文件保存在项目所在目录下。
						File savedFile = new File(uploadPath,newName);
						try
						{
							item.write(savedFile);
						}
						catch(Exception e)
						{
						}
						jsary.put(temjso);
					}
				}else
				{
					JSONObject temjso = new JSONObject(new LinkedHashMap());
					String oldName = item.getFieldName();// 获取上传的文件名
					String[] attAry = oldName.split("\\.");
					String strAtt = "";
					if(attAry.length > 1)
						strAtt = attAry[attAry.length - 1];
					String newName = com.zxy.common.Com_Fun.Get_New_GUID().replace("-","")
							+ "." + strAtt;

					// 判断是否传输json长字符串数据
					if(oldName.lastIndexOf(".dat") != -1
							&& oldName.lastIndexOf(".dat") == oldName.length()
									- 4)
					{
						temjso.put("oldFileName",oldName);
						temjso.put("newFileName",oldName);
						long size = item.getSize();// 获取上传的文件大小(字节为单位)
						if((java.util.Objects.equals(oldName,null)
								|| oldName.equals("")) && size == 0)
							continue;// 跳到while检查条件
						try
						{
							this.uploadPath += "//hisdata";
							File file = new File(uploadPath);
							if(!file.exists() && !file.isDirectory())
							{
								file.mkdir();
							}

							this.uploadPath += "//" + FileDate;
							file = new File(uploadPath);
							if(!file.exists() && !file.isDirectory())
							{
								file.mkdir();
							}

							// 表单信息
							// 写入保存成json文件
							FileOutputStream fos = new FileOutputStream(uploadPath
									+ "//" + oldName);
							fos.write(item.get());
							fos.flush();
							fos.close();
						}
						catch(Exception e)
						{
						}
						jsary.put(temjso);
					}else
					{
						temjso.put(Com_Fun.getLowUpp("oldFileName"),oldName);
						temjso.put(Com_Fun.getLowUpp("newFileName"),newName);

						long size = item.getSize();// 获取上传的文件大小(字节为单位)
						if((java.util.Objects.equals(oldName,null)
								|| oldName.equals("")) && size == 0)
							continue;// 跳到while检查条件
						try
						{
							// 表单信息
							String tName = item.getFieldName();
							String strISO = "";
							strISO += new String(item.getString().getBytes("iso-8859-1"),"utf-8");
							// 解码base64
							BASE64Decoder decoder = new BASE64Decoder();
							byte[] data = decoder.decodeBuffer(strISO.replace("data:image/jpeg;base64,",""));
							for(int i = 0;i < data.length;i++)
							{
								if(data[i] < 0)
								{
									data[i] += 256;
								}
							}

							String[] attAry2 = newName.split("\\.");
							String strAtt2 = "";
							if(attAry2.length > 1)
								strAtt2 = attAry[attAry.length - 1];
							if(!strAtt2.toUpperCase().equals("JPG"))
								newName = attAry[0] + ".jpg";
							// 写入保存成jpeg文件
							FileOutputStream fos = new FileOutputStream(uploadPath
									+ "//" + newName);
							fos.write(data);
							fos.flush();
							fos.close();
						}
						catch(Exception e)
						{
						}
						jsary.put(temjso);
					}
				}
			}
			jso.put("A01_UpLoadFile",jsary);
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,this.toString());
		}
		try
		{
			String strResult = jso.toString();
			out.write(strResult.getBytes(Com_Para.U_CODE));
			out.flush();
			out.close();
		}
		catch(Exception e)
		{
			String strError = "{\"A01_UpLoadFile\":[{\""+Com_Fun.getLowUpp("s_result")+"\":\"0\",\""+Com_Fun.getLowUpp("error_desc")+"\":\"附件大小超过40M或附件类型不正确,info:"
					+ e.getMessage() + "\"}]}";
			out.write(strError.getBytes(Com_Para.U_CODE));
			out.flush();
			out.close();
		}
	}

	public void init() throws ServletException
	{
		if(com.zxy.common.Com_Para.UpLoad_File.equals(""))
		{
			uploadPath = Com_Fun.GetAbsPath() + "files";
			tempPath = Com_Fun.GetAbsPath() + "temp";
		}else
		{
			uploadPath = com.zxy.common.Com_Para.UpLoad_File;
			tempPath = com.zxy.common.Com_Para.UpLoad_File + "//temp";
		}

		File uploadFile = new File(uploadPath);
		if(!uploadFile.exists())
		{
			uploadFile.mkdirs();
		}
		File tempPathFile = new File(tempPath);
		if(!tempPathFile.exists())
		{
			tempPathFile.mkdirs();
		}
	}
}